package com.student.dms;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.room.rxjava3.EmptyResultSetException;

import com.chivorn.smartmaterialspinner.SmartMaterialSpinner;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.luck.picture.lib.utils.ToastUtils;
import com.student.db.AccountDao;
import com.student.db.AccountEntity;
import com.student.db.AppDatabase;
import com.student.db.RoomDao;
import com.student.db.RoomEntity;
import com.student.dms.databinding.ActivityRegisterBinding;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class RegissterActivity extends BaseActivity {

    private ActivityRegisterBinding activityRegisterBinding;
    private AccountEntity accountEntity;
    private RoomEntity roomEntity;
    private List<String> userNames;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityRegisterBinding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(activityRegisterBinding.getRoot());
        activityRegisterBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(TitleBar titleBar) {
                finish();
            }
        });
        activityRegisterBinding.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String editUsername = activityRegisterBinding.editUsername.getText().toString().trim();
                String editNickname = activityRegisterBinding.editName.getText().toString().trim();
                String editPhoneNumber = activityRegisterBinding.editPhoneNumber.getText().toString().trim();
                String editRoomNo = activityRegisterBinding.editRoomNo.getText().toString().trim();
                String editPassword = activityRegisterBinding.editPassword.getText().toString().trim();
                String editComfirmPassword = activityRegisterBinding.editComfirmPassword.getText().toString().trim();
                String floorNo = (String) activityRegisterBinding.spinner.getSelectedItem();
                //先检查所有输入不能为空
                if (checkInputIsNull(activityRegisterBinding.editUsername)
                        || checkInputIsNull(activityRegisterBinding.editName)
                        || checkInputIsNull(activityRegisterBinding.rgSelectSex)
                        || checkInputIsNull(activityRegisterBinding.rgAccountType)
                        || checkInputIsNull(activityRegisterBinding.editPhoneNumber)
                        || checkInputIsNull(activityRegisterBinding.editRoomNo)
                        || checkInputIsNull(activityRegisterBinding.editPassword)
                        || checkInputIsNull(activityRegisterBinding.editComfirmPassword)
                        || checkInputIsNull(activityRegisterBinding.spinner)) {
                    ToastUtils.showToast(RegissterActivity.this, "输入或选择不能为空！");
                    return;
                }
                //检查号码是11位
                if (editPhoneNumber.length() < 11) {
                    ToastUtils.showToast(RegissterActivity.this, "手机号码长度不能低于11！");
                    return;
                }

                //再检查确认密码要跟密码一样
                if (!TextUtils.equals(editPassword, editComfirmPassword)) {
                    ToastUtils.showToast(RegissterActivity.this, "确认密码请跟密码保持一致！");
                    return;
                }
                //再检查密码输入规则

                if (!checkPassword(editPassword)) {
                    ToastUtils.showToast(RegissterActivity.this, "请输入8-12位密码，必须包含大小写字母，数字和特殊字符！");
                    return;
                }

                AppDatabase roomDatabase = DMSApplication.getApplication().getRoomDatabase();
                AccountDao accountDao = roomDatabase.provideAccountDao();
                RoomDao roomDao = roomDatabase.provideRoomDao();
                Single<AccountEntity> studentFlow = accountDao.searchAccountByName(editUsername);
                Single<RoomEntity> roomFlow = roomDao.searchRooms(editRoomNo);

                disposable.add(studentFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(studentEntity -> {
                    //学生表不为空，查寝室表
                    ToastUtils.showToast(RegissterActivity.this, "该账号已被注册！");
                }, studentFlowThrowable -> {
                    if (studentFlowThrowable instanceof EmptyResultSetException) {
                        //查寝室表
                        disposable.add(roomFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(roomEntity -> {
                            //寝室有人判断是否大于6
                            List<String> userNames = roomEntity.getStudentUserNames();
                            if (null == userNames) {
                                userNames = new ArrayList<String>();
                            }
                            if (userNames.size() >= 6) {
                                ToastUtils.showToast(RegissterActivity.this, "该宿舍已满6人请换其他寝室！");
                            } else {
                                //插入账号
                                insetAccount(editUsername, editNickname, editPhoneNumber, editPassword, editRoomNo,floorNo,accountDao);
                                //更新宿舍信息
                                userNames.add(editUsername);
                                roomEntity.setStudentUserNames(userNames);
                                Completable updateRoom = roomDao.insert(roomEntity);
                                disposable.add(updateRoom.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(()->{
                                            ToastUtils.showToast(RegissterActivity.this, "更新宿舍信息成功！");
                                            activityRegisterBinding.titleBar.postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    finish();
                                                }
                                            },500);
                                        }));
                            }
                        }, roomFlowThrowable -> {
                            //寝室没人直接插入
                            if (roomFlowThrowable instanceof EmptyResultSetException) {
                                //账号表为空
                                //表空的直接插入账号
                                insetAccount(editUsername, editNickname, editPhoneNumber, editPassword,editRoomNo, floorNo,accountDao);
                                userNames = new ArrayList<String>();
                                userNames.add(editUsername);
                                roomEntity=new RoomEntity();
                                roomEntity.setRoomNo(editRoomNo);
                                roomEntity.setStudentUserNames(userNames);
                                Completable updateRoom = roomDao.insert(roomEntity);
                                disposable.add(updateRoom.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(()->{
                                            ToastUtils.showToast(RegissterActivity.this, "注册宿舍信息成功！");
                                            activityRegisterBinding.titleBar.postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    finish();
                                                }
                                            },500);
                                        }));
                            }
                        }));
                    }
                }));
            }
        });

        List<String> items = new ArrayList<>();
        for (int i = 1; i <=20; i++) {
            items.add(i+"");
        }
        activityRegisterBinding.spinner.setItem(items);
        activityRegisterBinding.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                String select = items.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

    }

    private void insetAccount(String editUsername, String editNickname, String editPhoneNumber, String editPassword, String editRoomNo,String floorNo,AccountDao studentDao) {
        accountEntity = new AccountEntity();
        //注册学生
        accountEntity.setUserName(editUsername);
        accountEntity.setName(editNickname);
        RadioButton selectedRadioButton = findViewById(activityRegisterBinding.rgSelectSex.getCheckedRadioButtonId());
        int sex;
        if (selectedRadioButton.getText().equals("男")) {
            sex = 1;
        } else {
            sex = 0;
        }
        RadioButton selectedRadioButton1 = findViewById(activityRegisterBinding.rgAccountType.getCheckedRadioButtonId());
        int type;
        if (selectedRadioButton1.getText().equals("学生")) {
            type = 0;
        } else {
            type = 1;
        }
        accountEntity.setSex(sex);
        accountEntity.setRoomNo(editRoomNo);
        accountEntity.setFloorNo(floorNo);
        accountEntity.setType(type);
        accountEntity.setPhoneNum(editPhoneNumber);
        accountEntity.setPassWord(editPassword);
        disposable.add(studentDao.insert(accountEntity).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() -> ToastUtils.showToast(RegissterActivity.this, "账号注册成功！"), insertstudentDaothrowable -> ToastUtils.showToast(RegissterActivity.this, "学生账号注册失败！  message: " + insertstudentDaothrowable.getMessage())));
    }

    private boolean checkInputIsNull(EditText editText) {
        return TextUtils.isEmpty(editText.getText().toString().trim());
    }

    private boolean checkInputIsNull(RadioGroup radioGroup) {
        return radioGroup.getCheckedRadioButtonId() == -1;
    }


    private boolean checkInputIsNull(SmartMaterialSpinner spinner) {
        Object selectedItem = spinner.getSelectedItem();
        return selectedItem==null;
    }


    public boolean checkPassword(String password) {
        // 定义正则表达式，用于验证密码格式
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[\\W_]).{8,12}$";
        // 编译正则表达式为模式对象
        Pattern pattern = Pattern.compile(regex);
        // 创建匹配器对象，用于匹配输入的密码字符串
        Matcher matcher = pattern.matcher(password);
        // 通过匹配器的matches方法判断是否匹配成功，返回结果
        return matcher.matches();
    }


}
